package ltd.dujiabao.dex.jdk.exe;

import java.lang.reflect.Method;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import org.springframework.beans.factory.BeanFactory;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.dex.core.DelayJobEntity;
import ltd.dujiabao.dex.core.emitter.Emitter;

/**
 * @author : DuJiabao
 * @Project : common-delay-executor
 * @Time : 2024/3/30 11:47
 * @Desc :
 */
@Slf4j
public class JdkEmitter implements Emitter {
    private final DelayJobEntity delayJob;

    private final ScheduledThreadPoolExecutor executor;

    private final BeanFactory beanFactory;

    public JdkEmitter(DelayJobEntity delayJob, ScheduledThreadPoolExecutor executor, BeanFactory beanFactory) {
        this.delayJob = delayJob;
        this.executor = executor;
        this.beanFactory = beanFactory;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        Object bean = beanFactory.getBean(delayJob.getImplementation());
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    method.invoke(bean, args);
                } catch (Exception e) {
                    log.info("error ", e);
                }
            }
        }, delayJob.getDelayTime(), delayJob.getTimeUnit());
        return null;
    }
}
